<?php
#### MANAGEMENT CONTROLLER #####################################################
class ManagementController {

	#### CONSTRUCTOR ###########################################################
	function ManagementController() {
		Base::getThis();

		// Set the page title
		$this->page_title = _('Management');
		if (url(3)) $this->page_title .= ' '.ucwords(url(3));

		// Perform default function
		invoke_method($this, url(3));
	}

	#### MAIN ##################################################################
	function main() {
		$title = $this->icon['home'].' '._('Management Home');
		$content = _('Welcome to the '.$this->config['name'].' Management Area').' <b>'.$this->sessvar['login']['username'].'</b><br />';
		$content .= _('You last logged in on').' <i>'.$this->sessvar['login']['last_login_datetime'].'</i> '._('using the IP address').' <i>'.$this->sessvar['login']['last_login_ip'].'</i><br /><br />';


		// Show something to open source users ;)
		if(stristr(php_uname(), 'linux')) $tux = '<img src="media/icons/tux.png" /> ';
		else $tux = NULL;

		if (strlen(php_uname()) > 50) $php_uname = '<a href="#" title="'.php_uname().'">'.substr(php_uname(), 0, 50).' ...</a>';
		else $php_uname = php_uname();

		$this->load->helper('statistics');

		// Output Logicfury Info
		$content .= '<h3>'.$this->icon['info'].' '.$this->config['name'].' '._('Info').':</h3>
			<div class="indent">'.
			_('Powered By').': <a href="http://logicfury.org" target="_blank">Logicfury</a><br />'.
			_('Version').': '.$this->common['version'].'<br />'.
			_('Running on').': '.$tux.$php_uname.'<br />'.
			_('Server Load').': '.server_load().'<br />'.
			_('Server Time').': '.date('d/m/y h:m:s', time()).'<br />'.
			_('Server Uptime').': '.server_uptime().'<br />';
		$content .= $this->icon['bug'].' <a href="http://code.google.com/p/logicfury/issues/entry" target="_blank">'._('Report a bug').'</a><br />';
		$content .= '<br /></div>';

		if (permission('sql_errors')) {
			// Output PHP Info
			$content .= '<h3>'.$this->icon['info'].' '._('PHP Info').': (<a href="'.url(1).'/management/php-info" target="_blank">'._('View PHP Info').'</a>)</h3>
				<div class="indent">'.
					_('Version').': '.phpversion().'<br />';
					if (zend_version()) $content .= _('Zend Engine Version').': '.zend_version().'<br />';
					$content .= '<br />
				</div>';

			// Calculate DB row count and size
			$result = $this->db->query('SHOW TABLE STATUS FROM '.$this->config['db']['name'], $this->db->connection['config']) or sql_error(__FILE__, __LINE__);
			$total_rows = $total_size = 0;
			while ($status = $this->db->fetchArray($result)) {
				$total_rows += $status['Rows'];
				$total_size += $status['Data_length'] + $status['Index_length'];
			}

			$this->load->helper('file');

			// Output MySQL Info
			$content .= '<h3>'.$this->icon['info'].' '._('MySQL Info').':</h3>
				<div class="indent">'.
					_('Version').': '.mysql_get_server_info().'<br />'.
					_('Rows').': '.$total_rows.'<br />'.
					_('Size').': '.convert_bytes($total_size).'<br /><br />
				</div>';
		}

		if (permission('cache_management_manage')) {
			// Link to Cache Management
			$content .= '<h3>'.$this->icon['cache'].' '._('Cache Management').':</h3>
				<div class="indent">
					'._('SQL Cache').': ';
						if ($this->config['sql_cache_enabled']) $content .= 'On';
						else $content .= 'Off';
					$content .= '<br />';
					$content .= _('HTML Cache').': ';
						if ($this->config['html_cache_enabled']) $content .= 'On';
						else$content .= 'Off';
					$content .= '<br /><a href="'.url(1).'/management/cache">'._('Cache Management').'</a><br /><br />
				</div>';
		}

		// Link to Management Log
		$content .= '<h3>'.$this->icon['log'].' '._('Management Log').':</h3>
			<div class="indent">
				<a href="'.url(1).'/management/log">'._('View Log').'</a>
			</div>';

		$this->output = box($title, $content);
	}

	#### PHP INFO ##############################################################
	function phpInfo() {
		phpinfo();
		die();
	}

	#### LOG ###################################################################
	function Log() {
		// Get pages from database
		$page = $this->page - 1; // Change page to match array as arrays start from 0 but pages from 1
		$sql = "SELECT username, datetime, action FROM ".$this->db->table['log']." ORDER BY datetime DESC LIMIT ".($page * 20).", 20";
		$result = $this->db->query($sql, $this->db->connection['log']) or sql_error(__FILE__, __LINE__);
		$logs = $this->db->fetchArray($result);

		// Total Pages
		$sql = "SELECT count(log_id) FROM ".$this->db->table['log'];
		$result = $this->db->query($sql, $this->db->connection['log']) or sql_error(__FILE__, __LINE__);
		list($total) = $this->db->fetchRow($result);

		// Load pagination library a build pagination links
		$pagination = $this->load->library('pagination');
		$pagination->setCount($total);
		$pagination->setUrl(url(1, 2));
		$pagination->setPerPage(20);
		$pagination->setCurrentPage($this->page);
		$pagination->buildPagination('right');

		// Load the table library and open a new table
		$table = $this->load->library('table');
		$table->open();
		$table->tr(
			$table->th(_('Action')).
			$table->th(_('Date'), 200, TRUE).
			$table->th(_('Performed By'), 130, TRUE)
			);

		// Loop through out pages and build our table rows
		if ($logs) foreach ($logs as $log) {
			$table->tr(
				$table->td($log['action']).
				$table->td(datetime('G:i \- d/m/y', $log['datetime']), TRUE).
				$table->td(''.$log['username'].'</a>', TRUE)
				);
		}
		else $table->tr($table->td(_('No actions have been logged yet'), TRUE, 3));

		// Close table
		$table->close();

		// Set output
		$title = $this->icon['log'].' '._('Management Log');
		$body =
			$pagination->output().
			$table->output().
			$pagination->output();

		// Send output back through box() template
		$this->output .= box($title, $body);

	}

	#### CACHE #################################################################
	function cache() {
		// Load the table library and open a new table
		$table = $this->load->library('table');
		$table->open();
		$table->tr(
			$table->th(_('Cache File')).
			$table->th(_('Action'), 50, TRUE)
		);

		$cache_files = array();
		if ($dir = opendir('cache/')) {
			while (FALSE !== ($cache_file = readdir($dir))) {
				$cache_file = str_replace('.cache', '', $cache_file);
				if (!eregi('\.', $cache_file) && !eregi('status', $cache_file)) {
					$cache_files[] = $cache_file;
				}
			}
			closedir($dir);
		}
		sort($cache_files);

		if ($cache_files) foreach($cache_files as $cache_file) {
			$returned = TRUE;

			if (is_dir('cache/'.$cache_file)) $cache_icon = $this->icon['folder'];
			else $cache_icon = $this->icon['pages'];

			$table_title = $cache_icon.' '.ucwords(str_replace('_', ' ', $cache_file));
			$table_actions = '<a href="'.url(1).'/management/delete-cache-file" title="'._('Delete').'">'.$this->icon['delete'].'</a>';

			$table->tr(
				$table->td($table_title).
				$table->td($table_actions, TRUE)
				);
		}
		else $table->tr($table->td(_('No cache files exist'), TRUE, 3));

		// Close table
		$table->close();

		$title = $this->icon['cache'].' Cache Management';
		$body = $table->output();
		// Send output back through box() template
		$this->output .= box($title, $body);
	}

	#### DELETE CACHE FILE #####################################################
	function deleteCacheFile() {
		if(is_dir('cache/'.$cache_file)) {
			$cache_dir = $cache_file;
			$error = NULL;
			$br = FALSE;

			if ($dir = opendir('cache/'.$cache_dir.'/')) {
				while ($cache_file = readdir($dir)) {
					$cache_file = str_replace('.php', '', $cache_file);
					if (!strstr($cache_file, '.')) {
						if ($br == TRUE) $message .= '<br />';
						if (!update_cache($cache_dir.'/'.$cache_file, TRUE)) $error = 'Cache <b>'.$cache_dir.'/'.$cache_file.'</b> could not be deleted';
						$br = TRUE;
					}
				}
				closedir($dir);
			}
			if (!$error) {
				$this->feedback = notice(_('Cache').' <b>'.$cache_dir.'</b> '._('deleted successfully.'));
				return $this->main();
			} else {
				$this->feedback = notice($error, 'error');
				return $this->main();
			}

		} else {
			if (update_cache($cache_file, TRUE)) {
				$this->feedback = notice(_('Cache').' <b>'.$cache_file.'</b> '._('deleted successfully.'));
				return $this->main();
			} else {
				$this->feedback = notice(_('Cache').' <b>'.$cache_file.'</b> '._('could not be deleted.'), 'error');
				return $this->main();
			}
		}

	}

	#### DELETE ALL CACHE FILES ################################################
	function deleteAllCacheFiles() {
		$br = FALSE;

		$cache_files = array();
		if ($dir = opendir('cache/')) {
			while (FALSE !== ($cache_file = readdir($dir))) {
				$cache_file = str_replace('.php', '', $cache_file);
				if (!eregi('\.', $cache_file) && !eregi('status', $cache_file)) {
					$cache_files[] = $cache_file;
				}
			}
			closedir($dir);
		}
		sort($cache_files);

		foreach($cache_files as $cache_file) {

			if(is_dir('cache/'.$cache_file)) {
		                $cache_dir = $cache_file;

				if ($dir = opendir('cache/'.$cache_dir.'/')) {
					while ($cache_file = readdir($dir)) {
						$cache_file = str_replace('.php', '', $cache_file);
						if (!strstr($cache_file, '.')) {
							if ($br == TRUE) $message .= '<br />';
							if (update_cache($cache_dir.'/'.$cache_file, TRUE)) $message .= 'Cache <b>'.$cache_dir.'/'.$cache_file.'</b> deleted successfully!';
							else $message .= 'Cache <b>'.$cache_dir.'/'.$cache_file.'</b> could not be deleted!';
						}
					}
					closedir($dir);
				}
			} else {
				if ($br == TRUE) $message .= '<br />';
				if (update_cache($cache_file, TRUE)) {
					$this->feedback = notice(_('Cache').' <b>'.$cache_file.'</b> '._('deleted successfully.'));
					return $this->main();
				}
				else {
					$this->feedback = notice(_('Cache').' <b>'.$cache_file.'</b> '._('could not be deleted.'), 'error');
					return $this->main();
				}
			}
			$br = TRUE;
		}
	}
}
?>
